package com.hua.utility.encrypt;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

public class UtilEncryptUnReversSimple {

	private static final String KEY_SHA = "SHA";

	private static final String KEY_MD5 = "MD5";

	/**
	 * MD5加密(非可逆加密)
	 * 
	 * 广泛用于加密和解密技术，常用于文件校验。不管文件多大，经过MD5后都能生成唯一的MD5值。
	 * 
	 * @param data
	 * @return
	 * @throws NoSuchAlgorithmException
	 * 
	 */
	private static byte[] encryptMD5(byte[] data) throws NoSuchAlgorithmException {

		MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
		md5.update(data);
		return md5.digest();
	}

	/**
	 * SHA加密(非可逆加密)
	 * 
	 * 数字签名等密码学应用中重要的工具，被广泛地应用于电子商务等信息安全领域。较之MD5更为安全。
	 * 
	 * @param data
	 * @return
	 * @throws NoSuchAlgorithmException
	 * 
	 */
	private static byte[] encryptSHA(byte[] data) throws NoSuchAlgorithmException {

		MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
		sha.update(data);
		return sha.digest();

	}

	/**
	 * BASE64加密(可逆加密)
	 * 
	 * BASE64 严格地说，属于编码格式，而非加密算法
	 * 
	 * @param key
	 * @return
	 * 
	 */
	private static String encryptBASE64(byte[] key) {
		return (new BASE64Encoder()).encodeBuffer(key);
	}

	/**
	 * SHA、MD5 、 BASE64 的加密
	 * 
	 * @param oldPwd
	 * @return
	 */
	public static String encrypt(String oldPwd) {
		String newPwd = "";
		try {
			newPwd = doEncrypt(oldPwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newPwd;
	}

	private static String doEncrypt(String oldPwd) throws Exception {
		byte[] shaPwd = encryptSHA(oldPwd.getBytes());
		byte[] md5Pwd = encryptMD5((encryptBASE64(shaPwd)).getBytes());
		return encryptBASE64(md5Pwd).replaceAll("\n", "").replaceAll("\r", "");
	}

	/**
	 * 
	 * SHA、MD5 、 BASE64 密码比较
	 * 
	 * @param newPwd
	 * @param encryptPwd
	 * @return
	 */
	public static boolean compareEncrypt(String newPwd, String encryptPwd) {
		String newEncryptPwd = null;
		try {
			newEncryptPwd = doEncrypt(newPwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (newEncryptPwd != null && newEncryptPwd.equals(encryptPwd)) {
			return true;
		} else {
			return false;
		}
	}

}